﻿using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

namespace Common
{
    /// <summary>
    /// 验证帮助
    /// </summary>
    public class CaptchaHelper
    {
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        public static (Bitmap,string) GenerateCaptcha()
        {
            var width = 200;
            var height = 60;
            var fontNumber = 5;
            var lineNumber = 6;
            var letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789";
            Bitmap bitmap = new(width, height);
            Graphics graphic = Graphics.FromImage(bitmap);
            graphic.FillRectangle(new SolidBrush(Color.White), 0, 0, width, height);
            Font font = new(FontFamily.GenericSerif, width / fontNumber, FontStyle.Bold, GraphicsUnit.Pixel);
            Random random = new();
            StringBuilder sb = new();
            for (int i = 0; i < fontNumber; i++)
            {
                string letter = letters.Substring(random.Next(0, letters.Length - 1), 1);
                sb.Append(letter);
                graphic.DrawString(letter, font, new SolidBrush(Color.Black), i * width / fontNumber, random.Next(0, 15));
            }
            string code = sb.ToString();
            Pen linePen = new(new SolidBrush(Color.Black), 2);
            for (int i = 0; i < lineNumber; i++)
            {
                var point = new Point(random.Next(0, width - 1), random.Next(0, height - 1));
                var point2 = new Point(random.Next(0, width - 1), random.Next(0, height - 1));
                graphic.DrawLine(linePen, point, point2);
            }
            return (bitmap,code);
        }
        /// <summary>
        /// 位图转字节数组
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        public static byte[] BitmapToByte(Bitmap bitmap)
        {
            MemoryStream ms = new();
            bitmap.Save(ms,ImageFormat.Jpeg);
            return ms.ToArray();
        }
    }
}
